﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using Actuals.Business;
using Actuals.CoreDomain;
using Actuals.CoreDomain.Business;
using Actuals.CoreDomain.Data;
using Actuals.Common;
using System.Data;

namespace Actuals
{


    public partial class ShowActuals : System.Web.UI.Page
    {
        //private int gridId = 1;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["EmployeeId"] == null)
                 {
                     Response.Write("Please login!");
                     Response.End();
                 }

            Response.AddHeader("Cache-control", "no-store, must-revalidate,private,no-cache");
            Response.AddHeader("Pragma", "no-cache");
            Response.AddHeader("Expires", "0");

            Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);

            if (Request.QueryString["taskid"] != null)
            {
                IBusinessProject businessproject = new BusinessProject();
                List<IProject> projects = businessproject.GetProjects();
                ddlProject.DataSource = projects;
                ddlProject.DataTextField = "ProjectDescription";
                ddlProject.DataValueField = "ProjectId";
                ddlProject.DataBind();
                ddlProject.Items.Insert(0, "Select");

                IBusinessTask businessTask = new BusinessTask();
                ITask task = businessTask.GetTask(int.Parse(Request.QueryString["taskid"].ToString()));
                ddlProject.SelectedValue = task.ProjectId.ToString();
                FillRelease(task.ProjectId.ToString());
                ddlRelease.SelectedValue = task.ReleaseId.ToString();


                BindGridView();
                btnAddActual.Enabled = false;
            }
            else
            {

                // this.Page.ClientScript.RegisterForEventValidation("btnEdit");
                ClientScript.GetPostBackEventReference(this, string.Empty);

             //   IBusinessActual businessactual = new BusinessActual();
             //   btnAddActual.Enabled = businessactual.BtnAddActualDisable(int.Parse(Session["ProjectId"].ToString()),
                                                                       //  int.Parse(Session["ReleaseId"].ToString()));









                if (!Page.IsPostBack)
                {

                    IBusinessProject businessproject = new BusinessProject();
                    List<IProject> projects = businessproject.GetProjects();
                    ddlProject.DataSource = projects;
                    ddlProject.DataTextField = "ProjectDescription";
                    ddlProject.DataValueField = "ProjectId";
                    ddlProject.DataBind();
                    ddlProject.Items.Insert(0, new ListItem("Select","0"));
                    //ddlProject.SelectedValue = "Select";

                    ddlRelease.Items.Insert(0, new ListItem("Select", "0"));
                    //ddlRelease.SelectedValue = "Select";

                    txtFromDate.Text = DateTime.Now.AddDays(-5).Date.ToString("MM-dd-yyyy");
                    txtToDate.Text = DateTime.Now.Date.ToString("MM-dd-yyyy");

                    //BindGridView();


                }
                else
                {
                    if (Request.Form["__EVENTTARGET"] == "refresh")
                    {
                        BindGridView();
                    }
                }


            }


        }

        protected void ddlProject_OnSelectedIndexChanged(Object sender, EventArgs e)
        {
            FillRelease(ddlProject.SelectedValue);
        }

        protected void FillRelease(string projectId)
        {
            IBusinessRelease businessRelease = new BusinessRelease();
            IList<IRelease> releases = businessRelease.GetReleases(int.Parse(projectId));
            ddlRelease.DataSource = releases;
            ddlRelease.DataTextField = "Description";
            ddlRelease.DataValueField = "ReleaseId";
            ddlRelease.DataBind();
            ListItem select = new ListItem();
            select.Value = "0";
            select.Text = "Select";
            ddlRelease.Items.Insert(0, select);
        }

        private void ExportExcel(IList<IActual> actuals, string FileName)
        {

            //Create the DataGrid and perform the databinding

            DataGrid grid =

            new DataGrid();

            grid.DataSource = actuals;

            grid.DataMember = "actual";

            grid.DataBind();

            //Render the DataGrid control to a file

            using (StreamWriter sw = new StreamWriter(FileName, false, Encoding.Unicode))
            {

                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {

                    grid.RenderControl(hw);

                }

            }

            Response.Clear();

          //  this.EnableViewState = false;

            Response.Buffer = true;

            Response.AppendHeader("content-disposition", "attachment; filename=" + FileName + ".xls");

            Response.ContentType = "application/vnd.ms-excel";

            Response.Charset = "unicode";

            Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");



        }

        protected void btnDeleteShowActuals_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < gvResults.Rows.Count; i++)
                {
                    CheckBox cb = (CheckBox)gvResults.Rows[i].FindControl("chkShowActuals");
                    Label lbl = (Label)gvResults.Rows[i].FindControl("lblActualId");

                    if (cb.Checked)
                    {
                        string actualId = string.Empty;
                        if (lbl != null)
                        {
                            actualId = lbl.Text;

                            IBusinessActual businessActual = new BusinessActual();
                            businessActual.DeleteActual(int.Parse(actualId));
                        }
                    }


                }

                lblMsg.Text = "Deleted";
                BindGridView();





            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.Message;

            }


        }


        protected void gvResults_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            string actualId;

            switch (e.CommandName)
            {
                case "EditActual":
                    actualId = e.CommandArgument.ToString();
                    ClientScript.RegisterStartupScript(this.GetType(), "ShowUpdateActuals", "ShowUpdateActuals('" + actualId + "');", true);
                    //ClientScript.RegisterStartupScript(this.GetType(), "ShowUpdateActuals", "ShowUpdateActuals('" + actualId + "')"); //,'" + ddlProject.SelectedValue + "','" + ddlRelease.SelectedValue + "');", true);
                    //Response.Redirect("AddActuals.aspx?Mode=Edit&ActualId=" + actualId);
                    break;
                /* case "DeleteActual":
                     actualId = e.CommandArgument.ToString();
                     BusinessActual businessActual = new BusinessActual();
                     IActual actual = new Actual();
                     actual.ActualId = Int32.Parse(actualId);
                     businessActual.DeleteActual(actual);
                     //ClientScript.RegisterStartupScript(
                     //Response.Redirect("AddActuals.aspx?Mode=Edit&ActualId=" + actualId);))
                     break;*/

            }
        }


        protected string getTaskName(object taskId)
        {
            IBusinessTask businessTask = new BusinessTask();
            ITask task = businessTask.GetTask(int.Parse(taskId.ToString()));

            return string.Format("{0}-{1}", task.TaskShortName, task.Description);
        }

        protected string getEmpName(object employeeId)
        {


            IBusinessEmployee businessEmployee = new BusinessEmployee();
            IEmployee employee = businessEmployee.GetEmployee(int.Parse(employeeId.ToString()));

            return employee.NickName;
        }



        protected string getSubTaskName(object subTaskId)
        {

            IBusinessSubTask businessSubTask = new BusinessSubTask();
            ISubTask subTask = businessSubTask.GetSubTask(int.Parse(subTaskId.ToString()));
            return subTask.Description;
        }

        protected void BindGridView()
        {
            IBusinessActual businessActual = new BusinessActual();

         

            IList<IActual> actuals = new List<IActual>();

            if (Request.QueryString["taskid"] != null)
            {
                DateTime fromDate;
                string[] _date = Request.QueryString["startdate"].Split('-');

                fromDate = new DateTime(int.Parse(_date[2]), int.Parse(_date[0]), int.Parse(_date[1]));

                DateTime toDate;
                string[] _date1 = Request.QueryString["enddate"].Split('-');

                toDate = new DateTime(int.Parse(_date1[2]), int.Parse(_date1[0]), int.Parse(_date1[1]));

                int taskId = Convert.ToInt32(Request.QueryString["taskid"]);
                actuals = businessActual.GetActualsByTaskId(fromDate, toDate,
                                                                   taskId);

            }

            else
            {
                DateTime fromDate;
                string[] _date = txtFromDate.Text.Split('-');

                fromDate = new DateTime(int.Parse(_date[2]), int.Parse(_date[0]), int.Parse(_date[1]));

                DateTime toDate;
                string[] _date1 = txtToDate.Text.Split('-');

                toDate = new DateTime(int.Parse(_date1[2]), int.Parse(_date1[0]), int.Parse(_date1[1]));

                if (chkShowMyActual.Checked)

                    actuals = businessActual.GetActuals(fromDate, toDate,
                                                                       int.Parse(ddlProject.SelectedItem.Value),
                                                                      int.Parse(ddlRelease.SelectedValue));
                else
                {
                    actuals = businessActual.GetActualsForEmployee(fromDate, toDate,
                                                                    int.Parse(ddlProject.SelectedItem.Value),
                                                                   int.Parse(ddlRelease.SelectedItem.Value),
                                                                   int.Parse(Session["EmployeeId"].ToString()));

                }

               
            }

            Session["dsactuals"] = actuals;
            ViewState["DataSource"] = actuals;
            gvResults.DataSource = actuals;

            gvResults.DataBind();
        }

        protected void btnGetActuals_Click(object sender, EventArgs e)
        {
            BindGridView();
        }

         protected void btnExport_Click(object sender, EventArgs e)
        {
             IList<IActual> actuals= (IList<IActual>) Session["dsactuals"];
             ExportExcel(actuals, "somefile");
        }

        protected void gvResults_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (e.SortExpression == "date")
            {
                IList<IActual> actuals = (IList<IActual>)ViewState["DataSource"];

                IList<IActual> _actuals = new List<IActual>();
                if (e.SortDirection == SortDirection.Ascending)
                    _actuals = actuals.ToList().OrderBy(x => x.date).ToList();
                else
                    _actuals = actuals.ToList().OrderByDescending(x => x.date).ToList();

                ViewState["DataSource"] = _actuals;
                gvResults.DataSource = _actuals;
                gvResults.DataBind();


            }
            else if (e.SortExpression == "User")
            {
                IList<IActual> actuals = (IList<IActual>)ViewState["DataSource"];

                IList<IActual> _actuals = new List<IActual>();
                if (e.SortDirection == SortDirection.Ascending)
                    _actuals = actuals.ToList().OrderBy(x => x.EmployeeId).ToList();
                else
                    _actuals = actuals.ToList().OrderByDescending(x => x.EmployeeId).ToList();

                ViewState["DataSource"] = _actuals;
                gvResults.DataSource = _actuals;
                gvResults.DataBind();


            }

        }



    }
}